#!/usr/bin/env python3
"""
决策树分析后端示例
使用 smart_choice 框架进行决策树建模与分析
"""

from flask import Flask, request, jsonify
from flask_cors import CORS
import json
import sys
import os

# 添加 smart_choice 到路径（请根据实际安装路径调整）
# sys.path.append('/path/to/smart_choice')

try:
    from smart_choice import DataNodes, DecisionTree
except ImportError:
    print("警告: smart_choice 未安装，将使用模拟实现")
    # 模拟 smart_choice 类
    class DataNodes:
        def __init__(self):
            self.nodes = {}
        
        def add_node(self, node_id, node_type, **kwargs):
            self.nodes[node_id] = {
                'id': node_id,
                'type': node_type,
                **kwargs
            }
        
        def get_node(self, node_id):
            return self.nodes.get(node_id)
    
    class DecisionTree:
        def __init__(self, data_nodes):
            self.data_nodes = data_nodes
            self.edges = []
        
        def add_edge(self, source, target, label=None):
            self.edges.append({
                'source': source,
                'target': target,
                'label': label
            })
        
        def analyze(self):
            # 模拟分析结果
            return {
                'expected_value': 90.0,
                'optimal_path': ['开始决策', '选择A', '结果A'],
                'all_paths': [
                    {
                        'path': ['开始决策', '选择A', '结果A'],
                        'value': 100.0,
                        'probability': 0.5
                    },
                    {
                        'path': ['开始决策', '选择B', '结果B'],
                        'value': 80.0,
                        'probability': 0.5
                    }
                ]
            }

app = Flask(__name__)
CORS(app)  # 启用跨域支持

@app.route('/api/analyze', methods=['POST'])
def analyze_decision_tree():
    """
    分析决策树
    接收前端发送的决策树数据，使用 smart_choice 进行分析
    """
    try:
        data = request.get_json()
        
        # 创建 DataNodes 实例
        data_nodes = DataNodes()
        
        # 处理节点数据
        for node_data in data.get('dataNodes', []):
            node_id = node_data['id']
            node_type = node_data['type']
            
            if node_type == 'terminal':
                # 终止节点
                data_nodes.add_node(
                    node_id,
                    'terminal',
                    name=node_data['name'],
                    payoff=float(node_data.get('payoff', 0))
                )
            else:
                # 决策节点或概率节点
                branches = []
                for branch in node_data.get('branches', []):
                    branches.append({
                        'name': branch['name'],
                        'value': branch['value'],
                        'probability': float(branch.get('probability', 0)),
                        'target': branch['targetNode']
                    })
                
                data_nodes.add_node(
                    node_id,
                    node_type,
                    name=node_data['name'],
                    branches=branches
                )
        
        # 创建决策树
        decision_tree = DecisionTree(data_nodes)
        
        # 添加边
        for edge in data.get('decisionTree', {}).get('edges', []):
            decision_tree.add_edge(
                edge['source'],
                edge['target'],
                edge.get('label', '')
            )
        
        # 执行分析
        analysis_result = decision_tree.analyze()
        
        return jsonify({
            'success': True,
            'data': analysis_result
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/save', methods=['POST'])
def save_decision_tree():
    """
    保存决策树
    """
    try:
        data = request.get_json()
        tree_id = data.get('id', f"tree_{len(data)}")
        
        # 这里应该将数据保存到数据库或文件
        # 示例：保存到 JSON 文件
        with open(f"trees/{tree_id}.json", 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        
        return jsonify({
            'success': True,
            'id': tree_id,
            'message': '决策树保存成功'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/load/<tree_id>', methods=['GET'])
def load_decision_tree(tree_id):
    """
    加载决策树
    """
    try:
        # 从文件加载数据
        with open(f"trees/{tree_id}.json", 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        return jsonify({
            'success': True,
            'data': data
        })
        
    except FileNotFoundError:
        return jsonify({
            'success': False,
            'error': '决策树不存在'
        }), 404
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/trees', methods=['GET'])
def get_tree_list():
    """
    获取决策树列表
    """
    try:
        import os
        trees_dir = "trees"
        if not os.path.exists(trees_dir):
            os.makedirs(trees_dir)
        
        tree_files = [f for f in os.listdir(trees_dir) if f.endswith('.json')]
        tree_list = []
        
        for file_name in tree_files:
            tree_id = file_name.replace('.json', '')
            try:
                with open(f"{trees_dir}/{file_name}", 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    tree_list.append({
                        'id': tree_id,
                        'name': data.get('name', tree_id),
                        'created_at': os.path.getctime(f"{trees_dir}/{file_name}")
                    })
            except:
                continue
        
        return jsonify({
            'success': True,
            'data': tree_list
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/health', methods=['GET'])
def health_check():
    """
    健康检查
    """
    return jsonify({
        'status': 'ok',
        'message': '决策树分析服务运行正常'
    })

if __name__ == '__main__':
    # 创建 trees 目录
    import os
    if not os.path.exists('trees'):
        os.makedirs('trees')
    
    print("启动决策树分析服务...")
    print("API 地址: http://localhost:8000")
    print("健康检查: http://localhost:8000/api/health")
    
    app.run(host='0.0.0.0', port=8000, debug=True) 